import axios from 'axios'
import '@/store/index'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

const BASE_URL = 'http://www.ysqorz.top:8888/api/private/v1/'

export const request = creatBaseInstance()

// 通用的Axios的实例
function creatBaseInstance() {
    const instance = axios.create({
        baseURL: BASE_URL,
        timeout: 1000,
    });
    // 添加请求拦截器
    instance.interceptors.request.use((config) => {

        NProgress.start();
        config.headers.Authorization = window.sessionStorage.getItem('token')
        return config;
    });
    return instance
}

// 添加响应拦截器
let Interceptor = request.interceptors.response.use((response) => {
    window.vm.$message.success(response.data.meta.msg);
    NProgress.done();

    return response;
}, function (error) {
    window.vm.$message.error(error.data.meta.msg);
    return Promise.reject(error);
});


// 移除响应拦截器(可食用)
export function removeInterceptor() {
    request.interceptors.response.eject(Interceptor)
}

// 添加响应拦截器方法(可食用)
export function addInterceptor() {
    request.interceptors.response.use((response) => {
        window.vm.$message.success(response.data.meta.msg);
        return response;
    }, function (error) {
        window.vm.$message.error("访问失败");
        return Promise.reject(error);
    });
}